<?php
/**
 * Created by PhpStorm.
 * User: zd
 * Date: 2018/10/9
 * Time: 10:01
 */

namespace app\api\service;

use app\lib\exception\WorkException;
use think\Loader;
use think\Request;

Loader::import('WorkWx.callback.WXBizMsgCrypt',EXTEND_PATH);
Loader::import('WorkWx.api.src.ServiceCorpAPI.',EXTEND_PATH,'.class.php');
class WorkAI
{
    protected $encodingAesKey;
    protected $token;
    protected $corpId;
    private $suiteID;
    private $Secret;

    function __construct()
    {
        $this->encodingAesKey = config('ai.EncodingAESKey');
        $this->token = config('ai.Token');
        $this->suiteID = config('ai.SuiteID');
        $this->Secret = config('ai.Secret');
        $this->corpId = config('work.CorpID');
    }
    /**
     * 向企业微信返回通信标识
     * @return string
     */
    public function get(){
        $work = new Work($this->encodingAesKey, $this->token, $this->corpId);
        $sEchoStr =$work->get();
        return $sEchoStr;
    }
    /**
     * 处理微信返回的消息
     * @return mixed|string
     */
    public function getNotify(){
        $work = new Work($this->encodingAesKey, $this->token,$this->suiteID);
        $result = $work->getNotify();
        if (is_array($result)){
            return true;
        }else{
            return $result;
        }
    }
    /**
     * 获取预授权码
     * @return \ServiceCorpAPI
     */
    public function getPreAuthCode(){
        $work = new Work();
        $preAuthCode = $work->getPreAuthCode($this->suiteID,$this->Secret);
        return $preAuthCode;
    }
    /**
     *根据预授权码，获取永久授权码(测试)
     * @param $code
     * @return \GetPermanentCodeRsp
     */
    public function getTestPermanentCode($code){
        $work = new Work();
        $authInfo = $work->getPermanentCode($code,$this->suiteID,$this->Secret);
        return $authInfo;
    }
    /**
     *根据预授权码，获取永久授权码
     * @param $auth_code
     * @param $expires_in
     * @param $state
     * @return \GetPermanentCodeRsp
     */
    public function getPermanentCode($auth_code){
        $work = new Work();
        $authInfo = $work->getPermanentCode($auth_code,$this->suiteID,$this->Secret);
        return $authInfo;
    }
    /**
     * 设置应用配置信息
     */
    public function setAppConfig(){
        $work = new Work();
        $preAuthCode = $this->getPreAuthCode();
        $result =  $work->setAppConfig($preAuthCode,$this->suiteID,$this->Secret);
        return $result;
    }
    /**
     * 获取授权url
     * @return string
     */
    public function getAuthUrl($token){
        $work = new Work();
        $redirect_uri = urlencode('business.17jxyx.com/index/v1/ai/get_uri');
        $authUrl = $work->makeAuthUrl($this->suiteID,$this->Secret,$redirect_uri,$token);
        return $authUrl;
    }
    /**
     * 接收事件和消息
     * @param $CorpID
     * @return mixed|string
     */
    public function getEventInfo($CorpID){
        $getData = Request::instance()->param();
        $postData = file_get_contents('php://input');
        $sMsg = "";  // 解析之后的明文
        $wxcpt = new \WXBizMsgCrypt( $this->token,$this->encodingAesKey,$CorpID);
        $errCode =  $wxcpt->DecryptMsg($getData['msg_signature'],$getData['timestamp'],$getData['nonce'],$postData,$sMsg);
        if ($errCode == 0) {
            $data =Xml2Array($sMsg);
            $this->getInfoType($data);
            return $data;
        } else {
            return  "ERR: " . $errCode . "\n\n";
        }
    }
    /**
     * 获取用户信息
     * @param $code
     * @return mixed
     */
    public function getUserInfo($code){
        $work = new Work($this->encodingAesKey, $this->token,$this->suiteID);
        $suite_access_token = $work->getAccessToken($this->suiteID,$this->Secret);
        $url = "https://qyapi.weixin.qq.com/cgi-bin/service/getuserinfo3rd?access_token=".$suite_access_token."&code=".$code;
        $userInfo = curl_get($url);
        $data = json_decode($userInfo);
        if ($data->errcode == 0){
            return $data;
        }else{
            return false;
        }
    }

    /**
     * userId与openID互换
     * @param $userId
     * @return bool|mixed
     */
    public function userIdToOpenId($info,$userId){
        $work = new Work($this->encodingAesKey, $this->token,$this->suiteID);
        $suite_access_token = $work->getAccessToken($this->suiteID,$this->Secret);
        if (!cache($info->corpid)){
            $access_token = $work->get_access_token($suite_access_token,$info->permanent_code,$info->corpid);
        }else{
            $access_token = json_decode(cache($info->corpid));
        }
        $url = "https://qyapi.weixin.qq.com/cgi-bin/user/convert_to_openid?access_token=".$access_token;
        $pagrams = ["userid"=>$userId];
        $result = curl_post($url,$pagrams);
        $data = json_decode($result);
        if ($data->errcode == 0){
            return $data;
        }else{
            return false;
        }
    }

    /**
     * 发送消息
     * @param \app\api\model\Work $info
     * @param $pagrams
     * @return bool
     */
    public function deliveryMessage($info,$pagrams){
        $work = new Work($this->encodingAesKey, $this->token,$this->suiteID);
        $suite_access_token = $work->getAccessToken($this->suiteID,$this->Secret);
        if (!cache($info->corpid)){
            $access_token = $work->get_access_token($suite_access_token,$info->permanent_code_ai,$info->corpid);
        }else{
            $access_token = json_decode(cache($info->corpid));
        }
        $url = "https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token=".$access_token;
        $result = curl_post($url,$pagrams);
        $data = json_decode($result);
        if ($data->errcode == 0){
            return true;
        }else{
            return false;
        }
    }

    /**
     * 获取js-sdk所需参数
     * @param $jsapi_ticket
     * @param $url
     * @return mixed
     */
    public function getSignature($corpid,$url){
        $info = \app\api\model\Work::getCountInfo($corpid);
        $jsapi_ticket = $this->getWorkWxTicket($info,$url);
        $noncestr = getRandChar(10);
        $timesatmp = time();
        $signature = getWxJsapiTicket($noncestr,$jsapi_ticket,$timesatmp,$url);
        $data['timestamp'] = $timesatmp;
        $data['nonceStr'] = $noncestr;
        $data['signature'] = $signature;
        $data['appid'] = $corpid;
        return $data;
    }

    /**
     * 获取jsapi_ticket失败
     * @param $info
     * @param $base_url
     * @return mixed
     * @throws WorkException
     */
    public function getWorkWxTicket($info,$base_url){
        $data = cache('ticket_' . $info->corpid);
        if (!empty($data)){
            $ticket = $data;
        }else {
            $work = new Work($this->encodingAesKey, $this->token, $this->suiteID);
            $suite_access_token = $work->getAccessToken($this->suiteID, $this->Secret);
            if (!cache($info->corpid)) {
                $access_token = $work->get_access_token($suite_access_token, $info->permanent_code_ai, $info->corpid);
            } else {
                $access_token = json_decode(cache($info->corpid));
            }
            $url = 'https://qyapi.weixin.qq.com/cgi-bin/get_jsapi_ticket?access_token=' . $access_token;
            $result = curl_get($url);
            $data = json_decode($result);
            if ($data->errcode == 0) {
                $ticket = $data->ticket;
                cache('ticket_' . $info->corpid, $ticket, $data->expires_in);//缓存jsapi_ticket
            } else {
                throw new WorkException([
                    'msg' => '获取jsapi_ticket失败',
                ]);
            }
        }
        return $ticket;
    }

    /**
     * 获取素材
     * @param $corpid
     * @param $media_id
     * @return bool|int|mixed
     * @throws \Exception
     */
    public function getMaterial($corpid,$media_id,$wu_id){
        $info = \app\api\model\Work::getCountInfo($corpid);
        $work = new Work($this->encodingAesKey, $this->token, $this->suiteID);
        $suite_access_token = $work->getAccessToken($this->suiteID, $this->Secret);
        if (!cache($info->corpid)) {
            $access_token = $work->get_access_token($suite_access_token, $info->permanent_code_ai, $info->corpid);
        } else {
            $access_token = json_decode(cache($info->corpid));
        }
        $url = 'https://qyapi.weixin.qq.com/cgi-bin/media/get?access_token='.$access_token.'&media_id='.$media_id;
        $path = $this->createFolder();
        $name = md5(time() + rand(0, 1000));
        $result = $this->downAndSaveFile($url,$path .'/'.$name .'.amr');
        if ($result){
            $uplode = new FileUpload();//7牛云上传
            $result =  $uplode->uploadFile(ltrim($path.'/'.$name.'.amr', "."),$path . '/' . $name . '.amr',$wu_id,'audio');
            return $result;
        }else{
            throw new WorkException([
                'msg' => '下载素材失败',
            ]);
        }

    }

    /**
     * 授权添加
     * @param $uid
     * @param $result
     * @param $type
     * @return $this
     */
    public function authorizeAI($uid, $result,$type){
        $type['suitID'] = $this->suiteID;
        $info = \app\api\model\Work::creatWork($uid, $result,$type);
        return $info;
    }

    /**
     * 消息判断
     * @param $data
     */
    private function getInfoType($data){
        switch ($data['MsgType']){
            case 'text':
                break ;
            case 'image':
                break ;
            case 'voice':
                break ;
            case 'video':
                break ;
            case 'location':
                break ;
            case 'link':
                break ;
            case 'event':
                $this->getEvntType($data);
                break ;
        }
    }
    /**
     * 事件判断
     * @param $data
     * @return mixed
     */
    private function getEvntType($data){
        return $data;
    }

    /**
     * 创建文件夹
     * @return string
     */
    private function createFolder(){
        $data =  date('Ymd',time());
        $path = './audio/'.$data;
        if (!is_dir($path)){
            mkdir('./audio/'.$data,0777);
        }
        return $path;
    }

    /**
     * 下载语音文件
     * @param $url
     * @param $savePath
     * @return bool|int
     */
    public function downAndSaveFile($url,$savePath){
        ob_start();
        readfile($url);
        $img  = ob_get_contents();
        ob_end_clean();
        $size = strlen($img);
        $fp = fopen($savePath, 'a');
        $result = fwrite($fp, $img);
        fclose($fp);
        return $result;
    }

}